package algotithm.leetcode.trie.test206;

/**
 * @author zhouyanxiang
 * @Date 2021-04-2021/4/14-9:17
 * @Title 208. 实现 Trie (前缀树)
 */
public class Trie {

    public Trie[] next;
    public boolean isEnd;

    public Trie() {
        next = new Trie[26];
        isEnd = false;
    }

    public void insert(String word) {
        Trie node = this;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            int index = c - 'a';
            if (node.next[index] == null) {
                node.next[index] = new Trie();
            }
            node = node.next[index];
        }
        node.isEnd = true;
    }

    public boolean search(String word) {
        Trie node = searchPrefix(word);
        return node != null && node.isEnd;
    }

    public boolean startsWith(String prefix) {
        return searchPrefix(prefix) != null;
    }

    public Trie searchPrefix(String s) {
        Trie node = this;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            int index = c - 'a';
            if (node.next[index] == null) {
                return null;
            }
            node = node.next[index] ;
        }
        return node;
    }
}
